import React from "react";
import './index.css'
import { Button, Flex,Input,Checkbox,Form,Alert  } from "antd";
import type { FormProps } from 'antd';
import { UserOutlined,LockOutlined } from '@ant-design/icons';
import { useNavigate} from "react-router-dom";
import { loginApi } from "../../apis/user/user";
import { loginResponseData } from "../../apis/user/type";

type FieldType = {
  username: string;
  password: string;
};

const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
  console.log('Failed:', errorInfo);
};

const Login: React.FC = () => {
  const navigate = useNavigate()
  const onFinish: FormProps<FieldType>['onFinish'] =async (values) => {
    const data = {
      username:values.username,
      password:values.password
    }
    // 发起请求
    const result:loginResponseData = await loginApi(data)
    
    if(result.code == '200'){
      console.log('登录成功');
      alert('登录成功')
      setTimeout(()=>{
        navigate('/')
      },1500)
    }else{
      console.log('登录失败');
    }
  };
  return (
    <div className="wrap">
      <Flex vertical className="container">
        <Flex vertical className="text-align-center">
          <span className="title">数字马力</span>
          <div className="subTitle">数字马力培训pc大厦</div>
        </Flex>
        <Form name="normal_login" className="m-p-20"onFinish={onFinish}>
          <Form.Item name="username" rules={[{ required: true, message: '请输入账号!' }]}>
            <Input prefix={<UserOutlined />} placeholder="请输入账号" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!'},
              ({getFieldValue}) => ({
                validator(_, value) {  
                  if (value && value.length < 6) {  
                    return Promise.reject(new Error('密码长度至少为6位!'));  
                  }  
                  return Promise.resolve();  
                }, 
              })
            ]}
          >
            <Input.Password prefix={<LockOutlined />} type="password" placeholder="请输入密码"/>
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>自动登录</Checkbox>
            </Form.Item>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{width:'100%'}}>
              登录
            </Button>
            <Flex justify="flex-end">
              <span>没有账号？去<span onClick={()=>navigate('/register')} style={{color:'skyblue'}}>注册</span></span>
            </Flex>
          </Form.Item>
        </Form>
      </Flex>
    </div>
  );
};

export default Login;